<?php

namespace app\admin\controller;

use think\Db;
use think\Request;
use think\Validate;
use app\facade\Redis;
use think\facade\Env;

use app\models\{IntergralCate, IntergralGoods, User as Users, IntergralOrder, IntergralOrdergoods};

class Shop extends Base
{

    public function cate()
    {
        if ($this->request->isAjax()) {
            $model = new IntergralCate();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            if (!empty($post['title'])) {
                $where[] = ['name', 'like', '%' . $post['title'] . '%'];
            }
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order(["sort" => "desc", "id" => 'desc'])->limit($limit)->page($page)->select();
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view(null, []);
        }
    }

    public function cate_add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'name' => 'require',
            ], [
                'name.require' => '分类名称不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'msg' =>  $validate->getError()]);
            }
            $model = new IntergralCate();
            if (!empty($data['id'])) {
                $res = $model->allowfield(true)->save($data, ['id' => $data['id']]);
            } else {
                $res = $model->allowfield(true)->save($data);
            }
            if ($res) {
                return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
            }
            return json(['code' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
        } else {
            $model = new IntergralCate();
            $id = $this->request->get('id/d', 0);
            $row = $model->where('id', $id)->find();
            return view('', [
                'row' => $row,
            ]);
        }
    }


    public function cate_status()
    {
        $id = input('id');
        $field = input('field/s', '');
        if (!empty($id) && !empty($field)) {
            $model = new IntergralCate();
            $cate = $model->where(['id' => $id])->find();
            if (empty($cate)) {
                return json(['code' => 1, 'data' => [], 'msg' => '数据不存在,请刷新页面重试']);
            }
            switch ($field) {
                case 'isshow':
                    $status = $cate['isshow'] == 1 ? 2 : 1;
                    break;
                default:
                    return json(['code' => 1, 'data' => [], 'msg' => '数据类型错误,请刷新页面重试']);
                    break;
            }
            Db::startTrans();
            try {
                $model->where(['id' => $id])->update([$field => $status]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    }

    public function cate_del()
    {
        $id = input('id');
        if (!empty($id)) {
            $model = new IntergralCate();
            Db::startTrans();
            try {
                $model->where(['id' => $id])->delete();
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    }


    public function goods()
    {
        if ($this->request->isAjax()) {
            $model = new IntergralGoods();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            if (!empty($post['title'])) {
                $where[] = ['title', 'like', '%' . $post['title'] . '%'];
            }
            if (!empty($post['puton'])) {
                $where[] = ['puton', '=', $post['puton']];
            }
            if (!empty($post['cateid'])) {
                $where[] = ['cateid', '=', $post['cateid']];
            }
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order(["id" => 'desc'])->limit($limit)->page($page)->select();
            foreach ($list as $lists) {
                $lists['classname'] = '无';
                $lists['images'] = json_decode($lists['images'], true);
                if (!empty($lists['cateid'])) {
                    $lists['classname'] = (new IntergralCate())->where('id', $lists['cateid'])->value('name');
                }
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            $class = (new IntergralCate())->select();
            return view('', ['class' => $class]);
        }
    }

    public function goods_status()
    {
        $id = input('id');
        $field = input('field/s', '');
        if (!empty($id) && !empty($field)) {
            $model = new IntergralGoods();
            $cate = $model->where(['id' => $id])->find();
            if (empty($cate)) {
                return json(['code' => 1, 'data' => [], 'msg' => '数据不存在,请刷新页面重试']);
            }
            switch ($field) {
                case 'puton':
                    $status = $cate['puton'] == 1 ? 2 : 1;
                    break;
                case 'ishot':
                    $status = $cate['ishot'] == 1 ? 2 : 1;
                    break;
                default:
                    return json(['code' => 1, 'data' => [], 'msg' => '数据类型错误,请刷新页面重试']);
                    break;
            }
            Db::startTrans();
            try {
                $model->where(['id' => $id])->update([$field => $status]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    }

    //添加修改
    public function goods_add()
    {
        if ($this->request->isPost()) {
            $data = input('post.');
            if (!empty($data['images'])) {
                $data['images'] = json_encode($data['images'], true);
            }
            if (!empty($data['detail'])) {
                $data['detail'] = json_encode($data['detail'], true);
            }
            if (empty($data['id'])) {
                $result = (new IntergralGoods())->allowField(true)->save($data);
            } else {
                $result = (new IntergralGoods())->allowField(true)->save($data, ['id' => $data['id']]);
            }
            if ($result) {
                return json(['code' => 200, 'msg' => '操作成功']);
            } else {
                return json(['code' => 1, 'msg' => '操作失败']);
            }
        } else {
            $id = $this->request->get('id');
            $row = (new IntergralGoods())->where('id', $id)->find();
            $class = (new IntergralCate())->select();
            if (!empty($row['images'])) {
                $row['images'] = json_decode($row['images'], true);
            }
            if (!empty($row['detail'])) {
                $row['detail'] = json_decode($row['detail'], true);
            }
            return view('', ['row' => $row, 'class' => $class]);
        }
    }

    public function goods_del()
    {
        $id = input('id');
        if (!empty($id)) {
            $model = new IntergralGoods();
            Db::startTrans();
            try {
                $model->where(['id' => $id])->delete();
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    }

    public function order()
    {
        if ($this->request->isAjax()) {
            $model = new IntergralOrder();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            if (!empty($post['ordersn'])) {
                $where[] = ['ordersn', 'like', ($post['ordersn'] - pow(21, 8))];
            }
            if (!empty($post['status'])) {
                $where[] = ['status', '=', $post['status']];
            }
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order("id desc")->limit($limit)->page($page)->select();
            foreach ($list as $lists) {
                $lists['ordersn'] = $lists['id'] + pow(21, 8);
                $street = getdrees($lists['street'], 2);
                $lists['province_text'] = $street['province'];
                $lists['city_text'] = $street['city'];
                $lists['area_text'] = $street['area'];
                $lists['street_text'] = $street['street'];
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view(null, []);
        }
    }

    public function order_status()
    {
        if ($this->request->isAjax()) {
            $data = input();
            $validate = new Validate([
                'id' => 'require',
                'status' => 'require|in:1,2,3,4'
            ], [
                'id.require' => 'ID不能为空',
                'status.require' => '状态不能为空',
                'status.in' => '状态类型不正确',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'msg' =>  $validate->getError()]);
            }
            $order = (new IntergralOrder())->where('id', $data['id'])->find();
            if (empty($order)) {
                return json(['code' => 1, 'msg' =>  '订单不存在']);
            }
            switch ($data['status']) {
                case '1':
                    # code...
                    break;
                case '2':
                    if ($order['status'] != 1 && $order['status'] != 2) {
                        return json(['code' => 1, 'msg' =>  '订单未付款状态，无法执行该操作']);
                    }
                    if (empty($data['postalname']) || empty($data['postalcode'])) {
                        return json(['code' => 1, 'msg' =>  '请填写快递信息']);
                    }
                    break;
                case '3':
                    if ($order['status'] != 1 && $order['status'] != 2) {
                        return json(['code' => 1, 'msg' =>  '订单状态无法执行该操作']);
                    }
                    break;
                case '4':
                    if ($order['status'] != 1 && $order['status'] != 2 && $order['status'] != 3) {
                        return json(['code' => 1, 'msg' =>  '订单状态无法执行该操作']);
                    }
                    $user = (new Users())->where('id', $order['user_id'])->find();
                    if ($order['money'] > 0 && $order['payment'] > 0) {
                        $data['refund'] = 2;
                    }
                    break;
                default:
                    return json(['code' => 1, 'msg' =>  '订单类型错误']);
                    break;
            }
            Db::startTrans();
            try {
                (new IntergralOrder())->allowfield(true)->save($data, ['id' => $data['id']]);
                if ($data['status'] == 4 && !empty($user)) {
                    (new Users())->IntergralEdit($user['id'], $user['integral'], $order['total'], 3, $order['id'], '取消订单返回');
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'msg' => '操作失败']);
            }
            return json(['code' => 200, 'msg' => '操作成功']);
        }
    }

    public function order_edit()
    {
        $id = $this->request->get('id/d', 0);
        $row = (new IntergralOrder())->where('id', $id)->find();
        $arr = ['待付款', '待发货', '待收货', '已完成', '已取消'];
        if ($row) {
            $row['product'] = (new IntergralOrdergoods())->where('orderid', $row['id'])->select();
            $street = getdrees($row['street'], 2);
            $row['province_text'] = $street['province'];
            $row['city_text'] = $street['city'];
            $row['area_text'] = $street['area'];
            $row['street_text'] = $street['street'];
            $row['status_text'] = $arr[$row['status']] ?? '状态错误';
            $row['ordersn'] = $row['id'] + pow(21, 8);
        }
        return view('', [
            'row' => $row
        ]);
    }


    //添加修改
    public function yjgoods_add()
    {
        if ($this->request->isPost()) {
            $dataur = input('post.');
            $taobaourl = htmlspecialchars_decode($dataur['url']);
            $arr = parse_url($taobaourl);
            $goodsid = str_replace(array("/", ".html"), "", $arr['path'] ?? '');
            if (empty($goodsid)) {
                return json(['code' => 1, 'msg' => '获取失败']);
            }
            $url = 'https://api.jd.com/routerjson';
            $keys = '9b8623c35b954128888bafaf0e20b3f6';
            $jqdata = [
                'app_key' => 'ea11ff5dd1a89ed5323d5d526948d268',
                'timestamp' => date('Y-m-d H:i:s'),
                'method' => 'jd.union.open.goods.bigfield.query',
                'format' => 'json',
                'v' => '1.0',
                'sign_method' => 'md5',
                '360buy_param_json' => json_encode(["goodsReq" => ["skuIds" => [$goodsid]]], true)
            ];
            ksort($jqdata);
            $str = '';
            foreach ($jqdata as $k => $val) {
                $str .= $k . $val;
            }
            $strs = rtrim($str, '&');
            $sign = md5($keys . $strs . $keys);
            $jqdata['sign'] = strtoupper($sign);
            $res = api_curl($url, $jqdata);
            if (!is_array($res)) {
                $res = json_decode($res, true);
            }
            if (!empty($res['jd_union_open_goods_bigfield_query_responce']) && $res['jd_union_open_goods_bigfield_query_responce']['code'] == 0 && !empty($res['jd_union_open_goods_bigfield_query_responce']['queryResult'])) {
                $data = json_decode($res['jd_union_open_goods_bigfield_query_responce']['queryResult'], true);
                $data = $data['data'][0] ?? [];
                $path =  $_SERVER['DOCUMENT_ROOT'] . "/uploads/" . date('Ymd');
                $images = [];
                $detail = [];
                $jddetail = explode(',', $data['detailImages'] ?? '');
                foreach ($jddetail as $k => $v) {
                    if (count($detail) < 8 && $k > 0) {
                        $rrrm =  getImage($v, $path, '', 0);
                        if (!empty($rrrm['file_name'])) {
                            $detail[] = 'https://' . Env::get('app.api_url') . "/uploads/" . date('Ymd') . '/' . $rrrm['file_name'];
                        }
                    }
                }
                $jdimages = $data['imageInfo']['imageList'] ?? [];
                foreach ($jdimages as $k =>  $v) {
                    if (count($images) < 4 && $k > 0) {
                        $rrrm =  getImage($v['url'], $path, '', 0);
                        if (!empty($rrrm['file_name'])) {
                            $images[] = 'https://' . Env::get('app.api_url') . "/uploads/" . date('Ymd') . '/' . $rrrm['file_name'];
                        }
                    }
                }
                $images = json_encode($images, true);
                $detail = json_encode($detail, true);
                $save = [
                    'title' => $data['skuName'] ?? '',
                    'shortitle' => $data['skuName'] ?? '',
                    'price' => 0,
                    'intergral' => $dataur['price'] * 40,
                    'images' => $images,
                    'detail' => $detail,
                    'cateid' => $dataur['cateid'],
                    'sku' => rand(90, 110),
                    'sales' => 0
                ];
                $goods = (new IntergralGoods())->where('title', $save['title'])->find();
                if (!empty($goods)) {
                    return json(['status' => 1, 'msg' => '商品已存在']);
                }
                if (!empty($id)) {
                    $resul = (new IntergralGoods())->allowfield(true)->save($save, ['id' => $id]);
                } else {
                    $resul = (new IntergralGoods())->allowfield(true)->save($save);
                }

                if ($resul) {
                    return json(['code' => 200, 'msg' => '添加成功']);
                }
                return json(['status' => 1, 'msg' => '获取失败']);
            }
            return json(['status' => 1, 'msg' => '获取失败']);
        } else {
            $class = (new IntergralCate())->select();
            return view('', ['class' => $class]);
        }
    }
}
